//
//  PatientMedicalRecordViewController.m
//  StraightTrain
//
//  Created by mk on 15/11/26.
//  Copyright (c) 2015年 mk. All rights reserved.
//

#define PatientTableName        @"patient_mr_file"

#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

#import "PatientMedicalRecordViewController.h"
#import "IntentionMainViewController.h"

@interface PatientMedicalRecordViewController ()
{
    NSMutableArray * arrPicture;
    NSInteger updateIndex;
}

@end

@implementation PatientMedicalRecordViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [scrollMain setAlwaysBounceVertical:YES];
    arrPicture = [[NSMutableArray alloc] init];
    titleLabel.text = @"上传病历";
    [btnMore setTitle:@"跳过" forState:UIControlStateNormal];
    
    [btnNext setBackgroundImage:[[UIImage imageNamed:@"user_exit_btn.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateNormal];
   
    [self reloadPictureView];
    
}

//-(void)backNav:(id)sender
//{
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}

-(void)reloadPictureView
{
    int pictureW = (APP_CONTENT_WIDTH - 40-20)/3;
    int viewH = pictureW;
    if (arrPicture.count<3)//一排
    {
        viewH = pictureW;
    }
    else if (arrPicture.count<5 && arrPicture.count>=3)//2pai
    {
        viewH = (pictureW*2+10);
    }
    else if (arrPicture.count>=5)//3pai
    {
        viewH = (pictureW*3+20);
    }

    for (NSLayoutConstraint *constraints in [viewPicture constraints])
    {
        if (constraints.firstItem == viewPicture && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            constraints.constant = viewH;
            break;
        }
    }
    
    for (NSLayoutConstraint *constraints in [btnPickture1 constraints])
    {
        if (constraints.firstItem == btnPickture1 && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            if (constraints.constant == 60)
            {
                constraints.constant = pictureW;
                break;
            }
        }
    }
    
    btnPickture2.hidden = !(arrPicture.count>=1);
    btnPickture3.hidden = !(arrPicture.count>=2);
    btnPickture4.hidden = !(arrPicture.count>=3);
    btnPickture5.hidden = !(arrPicture.count>=4);
    btnPickture6.hidden = !(arrPicture.count>=5);
    btnPickture7.hidden = !(arrPicture.count>=6);
    btnPickture8.hidden = !(arrPicture.count>=7);
    btnPickture9.hidden = !(arrPicture.count>=8);
    
    [btnPickture1 setBackgroundImage:(arrPicture.count>=1)?[arrPicture objectAtIndex:0]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture2 setBackgroundImage:(arrPicture.count>=2)?[arrPicture objectAtIndex:1]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture3 setBackgroundImage:(arrPicture.count>=3)?[arrPicture objectAtIndex:2]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture4 setBackgroundImage:(arrPicture.count>=4)?[arrPicture objectAtIndex:3]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture5 setBackgroundImage:(arrPicture.count>=5)?[arrPicture objectAtIndex:4]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture6 setBackgroundImage:(arrPicture.count>=6)?[arrPicture objectAtIndex:5]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture7 setBackgroundImage:(arrPicture.count>=7)?[arrPicture objectAtIndex:6]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture8 setBackgroundImage:(arrPicture.count>=8)?[arrPicture objectAtIndex:7]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    [btnPickture9 setBackgroundImage:(arrPicture.count>=9)?[arrPicture objectAtIndex:8]:[UIImage imageNamed:@"patient_add_image.png"] forState:UIControlStateNormal];
    
    
}


-(IBAction)btnaddOrLookPicture:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    NSInteger clickTag = (btn.tag - 100);
    if (clickTag >= arrPicture.count)
    {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选照片",@"拍照", nil];
        [sheet showInView:self.view];
        
    }else
    {
        MFMWPhotoBrowser * browse = [[MFMWPhotoBrowser alloc] init];
        browse.mfDelegate = self;
        browse.delegate = self;
        browse.displayDeleteButton = YES;
        [browse setCurrentPhotoIndex:btn.tag-100];
        UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browse];
        [self presentViewController:nc animated:YES completion:nil];
    }
    
}



#pragma mark =======delegate======


#pragma mark photoBrowerNeedDeletePhoto
- (void)photoBrowerNeedDeletePhoto:(MFMWPhotoBrowser *)photoBrowser AtIndex:(int)index
{
    [arrPicture removeObjectAtIndex:index];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self reloadPictureView];
    
}

//查看大图
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return arrPicture.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto * photo = [MWPhoto photoWithImage:[arrPicture objectAtIndex:index]];
    return photo;
    
}

#pragma mark actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            
            Alert(alerTitle, @"您的设备无法使用相机", @"确定")
            return;
        }
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
        {
                //无权限
            Alert(alerTitle, @"您的设备不允许'名医主刀'访问您的相机,请到'设置'里面找到'名医主刀'并打开允许'名医主刀'访问相机功能", @"确定")
            return;
        }
    
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;  //相机
        [self presentViewController:picker animated:YES completion:nil];
        
    }else if (buttonIndex == 0)
    {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            Alert(alerTitle, @"您的设备无法使用'照片'", @"确定")
            return;
        }
        
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied)
        {
            //无权限
            Alert(alerTitle, @"您的设备不允许'名医主刀'访问您的照片,请到'设置'里面找到'名医主刀'并打开允许'名医主刀'访问照片功能", @"确定")
            return;
        }
        
        
        QBMFImagePickerController *selectPhoto = [[QBMFImagePickerController alloc] init];
        selectPhoto.QBMFDelegate = self;
        selectPhoto.maximumNumberOfSelection = (9 - [arrPicture count]);
        
        [self presentViewController:selectPhoto animated:YES completion:nil];
    }
}

#pragma mark - 选择照片发送协议方法 QBMFImagePickerController
- (void)imagePickerController:(QBMFImagePickerController *)imagePickerController didSelectPhtos:(NSArray *)photos
{
    [arrPicture addObjectsFromArray:photos];
    [self reloadPictureView];
}


//====================

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
    if (image)
    {
        [arrPicture addObject:image];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self reloadPictureView];
}




-(void)rightBarAction:(id)sender
{
  //跳过
    IntentionMainViewController * main = [[IntentionMainViewController alloc]initWithNibName:@"IntentionMainViewController" bundle:nil];
    main.strID = self.strID;
    [self.navigationController pushViewController:main animated:YES];
    
    //消除这个页面,保证在最后详情界面可直接跳转到首页
    NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    [array removeObjectAtIndex:array.count-2];
    self.navigationController.viewControllers = array;
}


#pragma mark 下一步
-(IBAction)btnNextClick:(id)sender
{
    if(arrPicture.count == 0)
    {
        Alert(alerTitle, @"至少请上传一张病历资料图片", @"确定")
        return;
    }
    updateIndex = 0;
    for (int i = 0; i < arrPicture.count; i++)
    {
        SetHUDStartText(@"上传图片中..")
        NSString * strUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"createPatientfileUrl"]);
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
        
        [dic setObject:self.strType forKey:@"patientFile[report_type]"];
        [dic setObject:self.strID forKey:@"patientFile[patient_id]"];
        
        [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"patientFile[username]"];
        [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"patientFile[token]"];
        
        
        [[HttpClient manager]UPLOADIMAGE:strUrl
                             uploadImage:[arrPicture objectAtIndex:i]
                         uploadImageName:@"patientFile[file_data]"
                              parameters:dic
                                 success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             if (updateIndex == (arrPicture.count-1))  //3
             {
                 SetHUDFinishedText(@"上传成功")
             }else
             {
               updateIndex = updateIndex+1;
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view);
         }];
        
        /*
        NSString * strGetToken = [NSString stringWithFormat:@"%@?tableName=%@",[gProjConfig.dicAllUrl objectForKey:@"uploadtoken"],PatientTableName];
        
        NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
        long long int currentTime=(long long int)time;
        NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
        NSData *imageData = UIImageJPEGRepresentation([arrPicture objectAtIndex:updateIndex],1);
        
        [[HttpClient manager]UPLOADIMAGEQINIU:strGetToken
                                  uploadImage:[arrPicture objectAtIndex:i]
                              uploadImageName:[NSString stringWithFormat:@"RealImageName%@.jpg",tempTime]
                                   parameters:nil
                                      success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             //向服务器提交数据
             DLog(@"==%@",responseObject);
             
             if ([responseObject isKindOfClass:[NSDictionary class]])
             {
                 NSInteger length = [imageData length]/1000;
                 
                 NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
                 
                 [dic setObject:PatientTableName forKey:@"appFile[tableName]"];
                 
                 [dic setObject:[NSString stringWithFormat:@"%ld",(long)length] forKey:@"appFile[size]"];
                 [dic setObject:@"jpg" forKey:@"appFile[type]"];
                 
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"remoteDomain"]) forKey:@"appFile[remoteDomain]"];//地址url
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"reomteKey"]) forKey:@"appFile[remoteKey]"];
                 
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"appFile[username]"];
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"appFile[token]"];
                 
                 if (updateIndex == (arrPicture.count-1))  //3
                 {
                     [self updateData:dic isEnd:YES];
                 }
                 else
                 {
                     [self updateData:dic isEnd:NO];
                 }
                 
                 updateIndex = updateIndex+1;
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view);
         }];
         */
    }
}

/*
#pragma mark 七牛上传成功 数据保存至数据库接口
-(void)updateData:(NSMutableDictionary *)requestDic isEnd:(BOOL)end
{
    
    NSString * strUpdateUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"saveappfile"]);
   // DLog(@"==%@==",[gProjConfig.dicAllUrl objectForKey:@"saveappfile"]);
    [[HttpClient manager]POST:strUpdateUrl
                   parameters:requestDic
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         DLog(@"=上传图片成功后回调=%@",responseObject);
         if (end)
         {
             SetHUDFinishedText(@"上传成功")
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view);
     }];
}
  */       

-(void)hudWasHidden:(MBProgressHUD *)hud
{
    
    IntentionMainViewController * main = [[IntentionMainViewController alloc]initWithNibName:@"IntentionMainViewController" bundle:nil];
    main.strID = self.strID;
    [self.navigationController pushViewController:main animated:YES];
    
    //消除这个页面,保证在最后详情界面可直接跳转到首页
    NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    [array removeObjectAtIndex:array.count-2];
    self.navigationController.viewControllers = array;

}



//-(IBAction)btnNextClick:(id)sender
//{
//  if(arrPicture.count>0)
//  {
//      for (int i = 0; i < arrPicture.count; i++)
//      {
//          SetHUDStartText(@"上传图片中..")
//          
//          NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
//          [dic setObject:self.strID forKey:@"patientFile[patient_id]"];
//          [dic setObject:self.strType forKey:@"patientFile[report_type]"];
//          [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"patientFile[token]"];
//          [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"patientFile[username]"];
//          
//          NSString * strUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"createPatientfileUrl"]);
//          [[HttpClient manager]UPLOADIMAGE:strUrl
//                               uploadImage:[arrPicture objectAtIndex:i]
//                              uploadImageName:@"patientFile[file_data]"
//                                parameters:dic
//                                   success:^(AFHTTPRequestOperation *operation, id responseObject)
//           {
//
//               if (i == (arrPicture.count-1))
//               {
//                   //DLog(@"==%@",responseObject);
//                    SetHUDHidden;
//                   IntentionMainViewController * main = [[IntentionMainViewController alloc]initWithNibName:@"IntentionMainViewController" bundle:nil];
//                   main.strID = self.strID;
//                   [self.navigationController pushViewController:main animated:YES];
//                   
//                   //消除这个页面,保证在最后详情界面可直接跳转到首页
//                   NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
//                   [array removeObjectAtIndex:array.count-2];
//                   self.navigationController.viewControllers = array;
//               }
//               
//           } failure:^(AFHTTPRequestOperation *operation, NSError *error)
//           {
//               SetHUDHidden;
//               HUDShowRequestError(error.domain, self.view);
//           }];
//      }
//
//  
//  }else
//  {
//     Alert(alerTitle, @"至少请上传一张病历资料图片", @"确定")
//  }
//
//}







- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
